package com.attendance.security.handler;

import com.attendance.ip.AddressUtils;
import com.attendance.security.info.pojo.LoginInfo;
import com.attendance.security.info.service.LoginInfoService;
import com.attendance.security.user.service.AbstractUserDetailsService;
import com.attendance.security.user.service.UserService;
import com.attendance.spring.SpringMvcUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;


/**
 * 登录成功处理程序
 *
 * @author 鵺丶
 * @date 2021/03/13
 */
@Component
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    UserService userService;
    @Autowired
    LoginInfoService loginInfoService;
    @Autowired
    AbstractUserDetailsService userDetailsService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取用户详情信息
        SpringMvcUtils.getSession().setAttribute("USER", userDetailsService.getUserDetailsForUser(userService.selectByName(authentication.getName())));

        //记录登录用户日志
        UserAgent userAgent = UserAgent.parseUserAgentString(SpringMvcUtils.getRequest().getHeader("User-Agent"));
        WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setName(authentication.getName());
        loginInfo.setIp(details.getRemoteAddress());
        loginInfo.setAddress(AddressUtils.getRealAddressByIP(details.getRemoteAddress()));
        loginInfo.setBrowser(userAgent.getBrowser().getName());
        loginInfo.setOs(userAgent.getOperatingSystem().getName());
        loginInfo.setLoginTime(new Date());
        loginInfoService.addLoginInfo(loginInfo);

        // 调用父类的方法把用户引导到未登录前要去的页面
        super.onAuthenticationSuccess(request, response, authentication);
    }
}